package com.dream.service.user.util;

import com.alibaba.fastjson.JSONObject;
import com.dream.common.model.response.BaseResponse;
import com.dream.common.model.response.ErrorCode;
import com.dream.service.image.bean.ImgUpS3Response;
import com.dream.service.image.impl.ImageServiceImpl;
import com.dream.service.user.config.UserConfig;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLDecoder;

/**
 * Created by ever on 2016/5/19.
 */
public class DownloadFileUtil {

    private static final Log logger = LogFactory.getLog(DownloadFileUtil.class);

    /**
     * 下载文件
     *
     * @param url           下载文件url
     * @param localFileName 本地完整的文件路径
     *                      返回值为true表示下载成功
     */
    public static boolean download(String url, String localFileName) throws Exception {
        URL httpurl = new URL(url);
        URLConnection conn = httpurl.openConnection();
        InputStream inStream = conn.getInputStream();
        FileOutputStream fos = new FileOutputStream(localFileName);
        byte[] b = new byte[102400];
        int j = -1;
        while ((j = inStream.read(b)) > -1) {
            fos.write(b, 0, j);
        }
        fos.close();
        inStream.close();
        return true;
    }

    /**
     * 先打开链接输入流，然后再把输入流上传到aws，不管http还是https
     * @param url 其他地址的图片url
     * @return 返回上传到aws的响应对象
     * @throws Exception
     */
    public static BaseResponse<ImgUpS3Response> downloadToAws(String url) {
        BaseResponse<ImgUpS3Response> response = new BaseResponse<ImgUpS3Response>();
        try {
            URL httpurl = new URL(url);
            URLConnection conn = httpurl.openConnection();
            conn.setConnectTimeout(8 * 1000);
            conn.setReadTimeout(8 * 1000);
            InputStream inStream = conn.getInputStream();
            response = ImageServiceImpl.upCidIconImg(inStream);
            if(inStream != null){
                inStream.close();
            }
            logger.info(JSONObject.toJSONString("outwall:"+ JSONObject.toJSONString(response)));
        }catch (Exception e){
            e.printStackTrace();
            ImgUpS3Response imgUpS3Response = new ImgUpS3Response();
            imgUpS3Response.setImageLink(UserConfig.DEFAULT_ICON);
            logger.info("inwall:"+JSONObject.toJSONString(imgUpS3Response));
            response.packData(false, ErrorCode.USERSTATUS_ICON_DOWNLOAD_FAIL.getCode(), e.getMessage(), null, imgUpS3Response);
        }
        return response;
    }

    public static void main(String[] args) throws Exception {
        String url = "https%3A%2F%2Flh3.googleusercontent.com%2F-XdUIqdMkCWA%2FAAAAAAAAAAI%2FAAAAAAAAAAA%2F4252rscbv5M%2Fs100%2Fphoto.jpg";
//        download(url,"d:/download.jpg");
        url = URLDecoder.decode(url, "UTF-8");
        System.out.println(url);
        BaseResponse<ImgUpS3Response> response = downloadToAws(url);
        JSONObject result = new JSONObject();
        if(response.isSuccess()){
            System.out.println(JSONObject.toJSON(response));
        }else{
            System.out.println(JSONObject.toJSON(response));
        }
    }
}
